package com.fengdi.book.middle;

import java.util.HashMap;
import java.util.HashSet;

public class MathProblem {
    public static class IsHappy {
        public boolean isHappy(int n) {
            if(n == 1) return true;
            int digit = n;
            HashSet<Integer> set = new HashSet<>();
            while(true) {
                int sum = 0;
                char[] digits = Integer.toString(digit).toCharArray();
                sum = this.sum(digits);
                if(sum == 1) return true;
                if(set.contains(sum)) return false;
                set.add(sum);
                digit = sum;
            }
        }

        private int sum(char[] chars) {
            int sum = 0;
            for (char aChar : chars) {
                sum = sum + (int) Math.pow(aChar - '0', 2);
            }
            return sum;
        }
    }

    public static class TrailingZeroes {
        public int trailingZeroes(int n) {
            int result = 0;
            while(n >= 5) {
                result += n / 5;
                n = n / 5;
            }
            return result;
        }
    }

    public static class TitleToNumber {
        // 其实就是一个27进制数转换的问题
        public int titleToNumber(String columnTitle) {
            HashMap<Character, Integer> alphabet = new HashMap<>();
            for(int i = 0; i < 26; i++) {
                alphabet.put((char)('A' + i), i + 1);
            }
            int result = 0;
            String s = new StringBuilder(columnTitle).reverse().toString();
            char[] chars = s.toCharArray();
            for(int i = 0; i < chars.length; i++) {
                result += alphabet.get(chars[i]) * (int)Math.pow(26, i);
            }

            return result;
        }
    }

    public static class MyPow {
        public double myPow(double x, int n) {
            double res = 1.0;
            int m = n;
            while(m != 0) {
                if(m % 2 != 0) {
                    res *= x;
                }
                x *= x;
                m /= 2;
            }
            return n < 0 ? 1 / res : res;
        }
    }

    public static class MySqrt {
        public int mySqrt(int x) {
            Long temp = 1L;
            while (true) {
                if (temp * temp > x) {
                    return (int) (temp - 1);
                }
                temp++;
            }
        }
    }
}
